package com.adopapa.nezhacloud.ddd.conf;

import org.hibernate.resource.jdbc.spi.StatementInspector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * spring:
  jpa:
    properties:
      hibernate:
        session_factory:
          statement_inspector: com.adopapa.nezhacloud.ddd.SqlStatementInspector 
 */

public class SqlStatementInspector implements StatementInspector {

	private static final long serialVersionUID = 1728006718693606801L;

	protected static Logger logger = LoggerFactory.getLogger(SqlStatementInspector.class);

	public final static ThreadLocal<String> tableNameLocal = new ThreadLocal<String>();

	public final static ThreadLocal<String> entityTableNameLocal = new ThreadLocal<String>();

	@Override
	public String inspect(String sql) {
		String tableName = this.getTableName();
		String entityTableName = this.getEntityTableName();
		if (tableName == null || entityTableName == null) {
			return sql;
		}
		String returnedSql = sql.toUpperCase().replace(entityTableName, tableName);
		logger.info(returnedSql);
		return returnedSql;
	}

	/**
	 * 获取需要分表名称
	 */
	private synchronized String getTableName() {
		return tableNameLocal.get();
	}

	/**
	 * 实体注解表名称
	 */
	private synchronized String getEntityTableName() {
		return entityTableNameLocal.get();
	}
	
	

}
